package com.gxa.core.recycling.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.core.recycling.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;

@Transactional(rollbackFor = {Throwable.class})
public class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    Mapper<T> mapper = null;

    @Override
    public T selectById(Serializable id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<T> selectByPage(Integer page, Integer size, T... t) throws IllegalAccessException {

        PageHelper.startPage(page, size);

        Example example = new Example(t[0].getClass());
        Example.Criteria criteria = example.createCriteria();
        List<T> list = null;
        if (t.length > 0) {
            Class<?> clazz = t[0].getClass();
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                String name = declaredField.getName();
                Object o = declaredField.get(t[0]);
                if (o != null) {
                    criteria.andLike(name, "%" + o.toString() + "%");
                }
            }

            list = mapper.selectByExample(example);
        } else {
            list = mapper.selectAll();
        }

        PageInfo<T> of = PageInfo.of(list);

        return of;
    }

    @Override
    public  List<T> select(T t){

        return mapper.select(t);

    }

    @Override
    public List<T> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public Integer updateById(T t) {
        return mapper.updateByPrimaryKeySelective(t);
    }

    @Override
    public Integer deleteById(Serializable id) {

        return   mapper.deleteByPrimaryKey(id);
    }

    @Override
    public T insert(T t) {

        int i=mapper.insertSelective(t);

        return null;
    }
}
